package com.york.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.york.oss.service.OssService;
import com.york.oss.utils.OssProperties;
import com.york.utils.exception.BusinessException;
import com.york.utils.exception.result.ResponseEnum;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @Description:头像上传实现类
 * @Data: 2022/3/10 16:39
 * @Author: yangboxiong
 * @Version
 * @since JDK 1.8
 */
@Service
public class OssServiceImpl implements OssService {
    @Override
    public String uploadFileAvatar(MultipartFile file) {
        // 工具类获取值
        String endpoint = OssProperties.END_POINT;
        String accessKeyId = OssProperties.ACCESS_KEY_ID;
        String accessKeySecret = OssProperties.ACCESS_KEY_SECRET;
        String bucketName = OssProperties.BUCKET_NAME;
        try {
            //创建OSSClient实例
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            //判断BUCKET_NAME是否存在
            if (!ossClient.doesBucketExist(bucketName)) {
                ossClient.createBucket(bucketName);
                ossClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
            }
            //上传文件流
            //构建日期路径
            String date = new DateTime().toString("yyyy/MM/dd/");
            // 获取上传文件的输入流
            InputStream inputStream = file.getInputStream();
            //获取文件名称
            String fileName = file.getOriginalFilename();
            //文件名生成
            fileName = UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."));
            String key = date + fileName;
            ossClient.putObject(bucketName, key, inputStream);
            // 关闭OSSClient。
            ossClient.shutdown();
            //阿里云文件绝对路径
            String url = "https://" + bucketName + "." + endpoint + "/" + key;
            return url;
        } catch (IOException e) {
            throw new BusinessException(ResponseEnum.UPLOAD_ERROR, e);
        }
    }
}
